<template>
  <div>
    <label class="el-checkbox">
        <span class="el-checkbox__input" :class="{'is-checked':isChecked}">
            <span class="el-checkbox__inner"></span>
            <input type="checkbox" :value="label" v-model="computedVal" class="el-checkbox__original" />
        </span>
        <span class="el-checkbox__label">
            <slot></slot>
        </span>
    </label>
  </div>
</template>

<script>
import { computed, defineComponent } from 'vue-demi'
export default defineComponent({
    name:'el-checkbox',
    props:{
        value:{
            // 扩展 v-model 语法糖，所必需的props属性。需要与emit("input")配合
            type:[Boolean,Array],
            default:false,
        },
        label:{
            // 由于value已经被占用了，所以 使用label来与checkbox原生value属性作绑定
            type:String,
            default:""
        }
    },
    setup(props,{emit}){
        const computedVal = computed({
            get(){
                return props.value
            },
            set(newVal){
                // 扩展 v-model 语法糖
                emit("input",newVal)
            }
        })
        const isChecked = computed(()=>{
            if(typeof props.value == 'boolean'){
                return props.value
            }else{
                return props.value.includes(props.label)
            }
        })

        return {
            computedVal,
            isChecked
        }
    }
})
</script>

<style lang="scss">
@import "./index.scss";
</style>